#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
using PII = pair<int, int>;

const int N = 105;
int g[N][N], d[N][N], n, m;

int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1};

int dfs()
{
    queue<PII> q;
    q.push({0, 0});
    while(q.size())
    {
        int k = q.size();
        while(k--)
        {
            auto cur = q.front(); q.pop();
            for(int i = 0; i < 4; ++i)
            {
                int x = cur.first + dx[i], y = cur.second + dy[i];
                if(x < 0 || y < 0 || x >= n || y >= m || g[x][y] || d[x][y] != -1) continue;
                d[x][y] = d[cur.first][cur.second] + 1;
                q.push({x, y});
            }
        }
    }
    return d[n - 1][m - 1];
}

int main()
{
    cin >> n >> m;
    for(int i = 0; i < n; ++i) for(int j = 0; j < m; ++j) cin >> g[i][j];
    memset(d, -1, sizeof(d));
    d[0][0] = 0;
    
    cout << dfs();
    
    return 0;
}